<template>
  <div class="login">
    <div class="contents">
      <div class="left_view">
        <div class="logos">
          <img src="https://anhuiyaoying.com/jiecunyun/logo.png" alt="">
          <span>捷存云进销存</span>
        </div>
        <img class="bg_img" src="../assets/img/login-background.jpg" alt="">
        <div></div>
      </div>
      <div class="right_view">
        <div class="title">捷存云后台管理系统</div>
        <div class="form_view">
          <div class="login_form">
            <el-form
              ref="loginForm"
              :model="loginForm"
              :rules="loginRules"
              label-width="60px"
            >
              <el-row>
                <!-- <el-col :span="24">
                  <el-form-item label="版本">
                    <el-select
                      v-model="loginForm.version"
                      placeholder="请选择"
                      style="width: 200px"
                    >
                      <el-option
                        v-for="item in versions"
                        :key="item.value"
                        :label="item.name"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col> -->
                <el-col :span="24">
                  <el-form-item label="账号" prop="phone_no">
                    <el-input
                      v-model="loginForm.phone_no"
                      placeholder="请输入账号"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="密码" prop="password">
                    <el-input
                      v-model="loginForm.password"
                      type="password"
                      show-password
                      placeholder="请输入密码"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="btn">
            <el-button
              type="primary"
              style="width: 280px; height: 36px"
              @click="handleLogin"
              >登录</el-button
            >
          </div>
          <div class="functions">
            <div class="left">
              <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
            </div>
            <div class="rights">
              <!-- <div class="item" @click="goExperience">去体验</div> -->
              <div class="item" @click="showRegister=true">注册账号</div>
              <div class="item" style="margin-left: 16px" @click="forgetPassword">
                找回密码
              </div>
            </div>
          </div>
        </div>
        <div class="footer">
          <span>© 2025 安徽曜影网络科技有限公司. All rights reserved.</span>
          <span>皖ICP备2023029173号</span>
        </div>
      </div>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      title="重置密码"
      :visible.sync="open"
      width="560px"
      append-to-body
    >
      <el-form ref="form" :model="findForm" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="手机号">
              <el-input
                :maxlength="11"
                v-model="findForm.phone_no"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="display: flex;align-items: start;justify-content: space-between;">
            <el-form-item label="验证码">
              <el-input
                :maxlength="6"
                v-model="findForm.sms_code"
                placeholder="请输入"
              />
            </el-form-item>
            <el-button
              @click="getSMSCode('find')"
              :disabled="!canGetCode"
              style="width: 140px; height: 40px; margin-left: 16px"
              >{{ tips }}</el-button
            >
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="新密码">
              <el-input
                :maxlength="50"
                @blur="inputBlur($event, '1')"
                v-model="findForm.password"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="确认密码">
              <el-input
                :maxlength="50"
                @blur="inputBlur($event, '2')"
                v-model="findForm.surePsd"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :disabled="!btnCanClick"
          style="width: 80px"
          @click="resetPassword"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      title="注册账号"
      :visible.sync="showRegister"
      width="560px"
      center
      append-to-body
    >
      <el-form ref="form" :model="registerForm" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="手机号">
              <el-input
                :maxlength="11"
                v-model="registerForm.phone_no"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="display: flex;align-items: start;justify-content: space-between;">
            <el-form-item label="验证码">
              <el-input
                :maxlength="6"
                v-model="registerForm.sms_code"
                placeholder="请输入"
              />
            </el-form-item>
            <el-button
              @click="getSMSCode('register')"
              :disabled="!canGetCode"
              style="width: 140px; height: 40px; margin-left: 16px"
              >{{ tips }}</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="密码">
              <el-input
                :maxlength="50"
                @blur="inputBlurRegister"
                v-model="registerForm.password"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="企业名称">
              <el-input
                :maxlength="50"
                v-model="registerForm.corp_name"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          style="width: 80px"
          @click="register"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="showChooseCorp"
      width="40%" center append-to-body :close-on-click-modal="false">
      <div>
        <div class="tips_text">检测到您的账号绑定多个企业，请选择一个企业进行登录：</div>
        <el-radio-group class="tips_radios" v-model="chooseCorpId">
          <el-radio v-for="item in loginCompanys" :key="'corp_'+item.id" 
            :label="item.corp" class="item">{{ item.corp_show.corp_name }}</el-radio>
        </el-radio-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showChooseCorp = false">取 消</el-button>
        <el-button class="btn_primary_color" @click="chooseOK">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { login, register, queryCorps, resetPsd } from "@/api/login";
import { sendMsg } from "@/api/unicloudApi";
import Cookies from "js-cookie";
import { setToken } from '@/utils/auth'

export default {
  name: "Login",
  data() {
    return {
      loading: false,
      showChooseCorp: false,
      open: false,
      showRegister: false,
      codeUrl: "",
      cookiePassword: "",
      loginForm: {
        version: 1,
        phone_no: "",
        password: "",
        rememberMe: false,
      },
      loginRules: {
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" },
        ],
        phone_no: [
          { required: true, trigger: "blur", message: "账号不能为空" },
        ],
      },
      findForm: {
        phone_no: "",
        sms_code: "",
        password: "",
        surePsd: "",
      },
      registerForm: {
        phone_no: '',
        password: '',
        sms_code: '',
        corp_name: ''
      },
      versions: [{ name: "企业版", value: 1 }],
      tips: "获取验证码",
      canGetCode: true, //是否可以点击获取验证码
      lastSeconds: null,
      btnCanClick: false, //确认按钮是否可点击
      loginCompanys: [],  //多个企业
      chooseCorpId: ''
    };
  },
  mounted() {
    this.getCookie();
  },
  methods: {
    // 从缓存中获取
    getCookie() {
      const phone_no = Cookies.get("phone_no");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        version: 1,
        phone_no: phone_no === undefined ? this.loginForm.phone_no : phone_no,
        password: password === undefined ? this.loginForm.password : password,
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    // 购买版本
    buyVersion() {
      this.$router.push('buyPackage')
    },
    // 注册
    register() {
      if (!this.registerForm.sms_code) {
        this.$message.error("请填写短信验证码");
        return;
      }

      register(this.registerForm).then(res => {
        if (res.code == 200){
          this.$message.success("注册成功");
        }
        this.showRegister = false
      })
    },
    // 找回密码
    forgetPassword() {
      this.open = true;
    },
    inputBlurRegister(e) {
      let txt = e.target.value;
      if (!txt) return;
      let reg = /^[A-Za-z\d@$!%*?&#_]{6,}$/;
      if (reg.test(txt)) {
        this.registerForm.password = txt;
      } else {
        this.$message.error(
          "密码长度至少6位数且只能包含字母、数字和特殊符号"
        );
        this.registerForm.password = "";
      }
    },
    // input失焦事件
    inputBlur(e, type) {
      let txt = e.target.value;
      if (!txt) return;

      if (type == "1") {
        let reg = /^[A-Za-z\d@$!%*?&#_]{6,}$/;
        if (reg.test(txt)) {
          this.findForm.password = txt;
        } else {
          this.$message.error(
            "密码长度至少6位数且只能包含字母、数字和特殊符号"
          );
          this.findForm.password = "";
        }
      } else {
        if (this.findForm.password != txt) {
          this.$message.error("两次密码输入不一致，请重新输入");
          this.findForm.surePsd = "";
        } else {
          this.findForm.surePsd = txt;
        }
      }

      this.btnCanClick = false;
      if (this.findForm.password && this.findForm.surePsd) {
        this.btnCanClick = true;
      }
    },
    // 获取短信验证码
    getSMSCode(type) {
      let flag = false;
      let reg = /^1\d{10}$/;
      if (type == 'find'){
        if (this.findForm.phone_no.length != 11) {
          flag = true;
        } else if (!reg.test(this.findForm.phone_no)) {
          flag = true;
        }
      }else{
        if (this.registerForm.phone_no.length != 11) {
          flag = true;
        } else if (!reg.test(this.registerForm.phone_no)) {
          flag = true;
        }
      }

      if (flag) {
        this.$message.error("请输入正确的手机号码");
        return;
      }

      if (this.canGetCode) {
        let that = this;
        that.canGetCode = false;
        let params = {}
        if (type == 'find'){
          params.phone = this.findForm.phone_no
        }else {
          params.phone = this.registerForm.phone_no
        }
        sendMsg(params).then((res) => {
          that.$message({
            message: "发送成功",
            type: "success",
          });
          that.lastSeconds = 60;

          let timer = setInterval(() => {
            if (that.lastSeconds < 0) {
              clearInterval(timer);
              that.tips = "重新获取";
              that.canGetCode = true;
            } else {
              that.lastSeconds--;
              that.tips = that.lastSeconds + "秒后重新获取";
            }
          }, 1000);
        });
      }
    },
    // 重置密码
    resetPassword() {
      if (!this.findForm.sms_code) {
        this.$message.error("请填写短信验证码");
        return;
      }

      resetPsd({
        phone_no: this.findForm.phone_no,
        sms_code: this.findForm.sms_code,
        password: this.findForm.password,
      }).then((res) => {
        if (res.code == 200) {
          this.open = false;
          this.$message({
            message: "密码重置成功",
            type: "success",
          });
        }
      });
    },
    // 登录方法
    handleLogin() {
      var that = this;
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          const phone_no = this.loginForm.phone_no.trim();
          const password = this.loginForm.password.trim();

          if (this.loginForm.rememberMe) {
            Cookies.set("phone_no", phone_no, { expires: 30 });
            Cookies.set("password", password, { expires: 30 });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("phone_no");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }

          login({ phone_no, password }).then((res) => {
            if (res.code == 200) {
              // 存储token
              setToken(res.data.login_token);
              this.$store.commit("SET_TOKEN", res.data.login_token);
              // 查询该用户可选择的公司列表
              that.queryCorpLists((_res) => {
                that.$store
                  .dispatch("Login", _res)
                  .then((_res_) => {
                    that.loading = false;
                    if (_res_.data.Token) {
                      that.$router.push('manage');
                    }
                  })
                  .catch(() => {
                    this.loading = false;
                  });
              });
            }
          });
        }
      });
    },
    queryCorpLists(callback) {
      queryCorps().then((res) => {
        let list = res.data;
        if (list.length > 1){
          this.loginCompanys = list
          this.showChooseCorp = true
          this.loading = false
        }else{
          callback(list[0].corp);
        }
      });
    },
    chooseOK() {
      this.$store
        .dispatch("Login", this.chooseCorpId)
        .then((_res_) => {
          if (_res_.data.Token) {
            this.$router.push('manage');
          }
        })
        .catch(() => {
          this.loading = false;
        });
    }
  },
};
</script>

<style lang="less" scoped>
@import '../style/mixin';
.login {
  width: 100%;
  height: 100%;
  overflow-y: hidden;
  background-color: #96d4fe;
  display: flex;
  align-items: center;

  .login_bg {
    height: 100%;
  }
  .contents {
    margin: 0 auto;
    width: 60%;
    height: 80%;
    position: relative;
    background: #fff;
    display: flex;
    border-radius: 16px;

    .left_view {
      background: #d3e3fd;
      border-top-left-radius: 16px;
      border-bottom-left-radius: 16px;
      padding: 30px 0;
      width: 50%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .logos {
        display: inline-flex;
        align-items: center;
        gap: 10px;
        padding-left: 40px;
        img {
          width: 40px;
          height: 40px;
          border-radius: 10px;
        }
        span {
          font-size: 18px;
          font-weight: bold;
          color: @blue;
        }
      }
      .bg_img {
        width: 100%;
        height: auto;
      }
    }

    .right_view {
      width: 50%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      position: relative;

      .title {
        text-align: center;
        font-size: 20px;
        font-weight: bold;
        margin-bottom: 50px;
        letter-spacing: 1px;
        margin-top: 80px;
      }
      .login_form {
        width: 280px;
        margin: 0 auto;
      }
      .functions {
        display: flex;
        margin: 0 auto;
        margin-top: 20px;
        align-items: center;
        justify-content: space-between;
        width: 280px;

        .left {
          margin-left: 0;
        }
        .rights {
          display: flex;
          justify-content: flex-end;
          .item {
            cursor: pointer;
            font-size: 14px;
          }
          .item:hover {
            color: #4095e5;
          }
        }
      }
      .btn {
        text-align: center;
        margin-top: 20px;
      }
      .footer {
        margin-bottom: 8px;
        font-size: 12px;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8px;
      }
    }
  }
}
.tips_text {
  font-size: 15px;
  margin-bottom: 20px;
  letter-spacing: 0.5px;
}
.tips_radios {
  display: flex;
  flex-direction: column;
  padding-left: 30px;
  .item {
    padding: 10px 0;
  }
}
</style>
<style scoped>
.login /deep/ .el-checkbox {
  color: #000 !important;
}
.el-input /deep/ .el-input__inner {
  width: 220px;
}
.el-select {
  width: 220px !important;
}
.el-select /deep/ .el-input__inner {
  width: 220px;
}
</style>
